package cn.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class ChatClient {
    private final SocketChannel socketChannel;
    private final String username;

    public ChatClient() throws IOException {
        socketChannel=SocketChannel.open();
        socketChannel.configureBlocking(false);
        String HOST = "127.0.0.1";
        int PORT = 9999;
        InetSocketAddress address = new InetSocketAddress(HOST, PORT);

        if(!socketChannel.connect(address)){
            while (!socketChannel.finishConnect()){
                System.out.println("Client: 连接服务器端的同时, 我还可以干别的事");
            }
        }
        username=socketChannel.getLocalAddress().toString().substring(1);
        System.out.println("---------Client("+username+") is ready-----------");
    }

    //向服务端发送数据
    public void sendMsg(String msg) throws IOException {
        if (msg.equalsIgnoreCase("bye")){
            socketChannel.close();
            return;
        }
        msg=username+"说: "+msg;
        ByteBuffer buffer=ByteBuffer.wrap(msg.getBytes());
        socketChannel.write(buffer);
    }

    //从服务器加收数据
    public void receiveMsg() throws IOException {
        ByteBuffer buffer=ByteBuffer.allocate(1024);
        int size = socketChannel.read(buffer);
        if(size>0){
            String msg=new String(buffer.array());
            System.out.println(msg.trim());
        }
    }
}
